<template id="productItem">
  <div class="productItem" ref="productItem">
    <products
      ref="products"
      :productList="productList"
      :sortList="sortList"
      :page="page"
      :isShowSelect="isShowSelect"
      @click="buyProduct"
      @buyProductDeep="buyProductDeep"
      @changeSize="changeSize"
      @changePage="changePage"
      @changeTypeByPhone="changeTypeByPhone"
      @changeSort="changeSort"
      @changeSortByPhone="changeSortByPhone"
      @open="openSelect"
      @close="closeSelect"
      @clickPhoneType="clickPhoneType"
      @changeKind="changeKind"
      @getList="getList"
    />
  </div>
</template>

<script>
import MailBanner from "../MailBanner.vue";
import Products from "./components/Products.vue";
import { getDoodsListApi, createOrderApi, getGoodsOnebuyListApi } from "@/api";
import { iscode, getWidth, isWeixin, isIOS } from "@/utils";
import { mapState, mapMutations } from "vuex";
import { Message } from "element-ui";
import { Toast } from "vant";
export default {
  name: "ProductItem",
  components: { Products, MailBanner },
  data() {
    return {
      productList: [],
      page: {
        defaultPagination: 1,
        pageCount: 8,
        totalPages: 0
      },
      sortList: [
        {
          value: "",
          text: "默认排序"
        },
        {
          value: "goods_price desc",
          text: "价格降序"
        },
        {
          value: "goods_price asc",
          text: "价格升序"
        },
        {
          value: "create_time desc",
          text: "时间降序"
        },
        {
          value: "create_time asc",
          text: "时间升序"
        }
      ],
      typeValue: 1,
      sortValue: "",
      kindValue: "",
      isShowSelect: false,
      goodsCateId: "",
      isIos: false,
      mescroll: "",
      currentWidth: "",
      platform: 1, //  "platform":1PC 2手机
      is_one_buy: 0 //是否为1元购商品
    };
  },
  computed: {},
  methods: {
    //一元购列表
    async getGoodsOnebuyList() {
      let result = await getGoodsOnebuyListApi({
        page: this.page.defaultPagination,
        pagesize: this.page.pageCount
      });
      if (iscode(result)) {
        this.is_one_buy = 1;
        this.page.totalPages = result.result.count;
        this.productList = result.result.list;
        this.productList.map((item, index) => {
          this.$set(item, "price", item.money);
          this.$set(item, "goods_stock", item.stock);
          this.$set(item, "image", result.result.show_url + item.images[0]);
          this.$set(item, "icon", result.result.show_url + item.icon);
        });
      }
    },
    //商品列表
    async getDoodsList() {
      let result = await getDoodsListApi({
        goods_cate_id: this.kindValue,
        page: this.page.defaultPagination,
        pagesize: this.page.pageCount,
        orderby: this.sortValue
      });
      if (iscode(result)) {
        this.is_one_buy = 0;
        this.page.totalPages = result.result.count;
        this.productList = result.result.list;
        this.countTime(result, this.productList);
        this.productList.map((item, index) => {
          this.$set(item, "image", result.result.show_url + item.images[0]);
          this.$set(item, "icon", result.result.show_url + item.icon);
          this.$set(item, "now_time", result.result.now_time);
          let date, month, day, time;
          if (item.pre_start_time) {
            date = item.pre_start_time.split(" ")[0].split("-");
            month = date[1] + "月";
            day = date[2] + "日";
            time = month + day + item.pre_start_time.split(" ")[1].substr(0, 5) + "开售";
            this.$set(item, "sellTime", time);
            this.overTime(item);
          }
        });
      }
    },
    //获取列表数据
    getList(payload) {
      if (payload == 1) {
        this.getDoodsList();
      } else {
        this.getGoodsOnebuyList();
      }
    },
    //商品详情
    buyProduct(payload) {
      if (this.platform == 2) {
        window.localStorage.setItem("shopPath", this.$route.path);
      }
      let goodId = "";
      if (this.is_one_buy) {
        goodId = payload.goods_id;
      } else {
        goodId = payload.id;
      }
      this.$router.push({
        path: "/mail/productDetail",
        query: {
          id: goodId
        }
      });
    },

    // 点击购买直接跳转到确认订单界面
    buyProductDeep(payload) {
      if (payload.is_buy) {
        this.createOrder(payload);
      } else {
        this.$router.push({
          path: "/mail/productDetail",
          query: {
            id: payload.id
          }
        });
      }
    },
    async createOrder(payload) {
      let result = await createOrderApi({
        goods_id: payload.id,
        hashcode:
          "0x456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5",
        platform: this.platform
      });
      if (result.code == 0) {
        this.$router.push({
          path: "/mail/confirmProducts",
          query: {
            id: payload.id,
            order_sn: result.result.order.order_sn,
            order_id: result.result.order.id
          }
        });
      } else if (result.code == 200019) {
        if (getWidth() <= 768) {
          Toast(result.message);
          this.$router.push("/authentication");
        } else {
          Message({
            showClose: true,
            message: result.message,
            type: "error"
          });
        }
      } else {
        if (getWidth() <= 768) {
          Toast(result.message);
          this.$router.push("/login");
        } else {
          Message({
            showClose: true,
            message: result.message,
            type: "error"
          });
        }
      }
    },

    //分页
    changePage(page) {
      this.page.defaultPagination = page;
      this.getDoodsList();
    },
    changeSize(size) {
      this.page.pageCount = size;
      this.getDoodsList();
    },

    //单品、专辑选择
    changeTypeByPhone(payload) {
      this.typeValue = payload;
      this.$router.push("/mail/albumItem");
    },

    //选择类型
    changeKind(payload) {
      this.kindValue = payload;
      this.getDoodsList();
    },
    //排序选择
    changeSort(payload) {
      this.sortValue = payload;
      this.getDoodsList();
    },

    //排序选择
    changeSortByPhone(payload) {
      this.sortValue = payload;
      this.isShowSelect = false;
      this.getDoodsList();
    },

    openSelect() {
      this.isShowSelect = !this.isShowSelect;
    },
    closeSelect() {
      this.isShowSelect = false;
    },
    clickPhoneType(payload) {},

    //倒计时
    countTime(result, list) {
      list.map((item, index) => {
        if (item.is_buy == 0) {
          let startDate, endDate;
          if (this.isIos == true) {
            startDate = new Date(result.result.now_time.replace(/-/g, "/"));
            endDate = new Date(item.pre_start_time.replace(/-/g, "/"));
          } else {
            startDate = new Date(result.result.now_time);
            endDate = new Date(item.pre_start_time);
          }
          let now = startDate.getTime();
          let end = endDate.getTime();
          let leftTime = end - now;
          if (leftTime * 1 > 0) {
            this.$set(item, "countTimeStatus", 1);
          } else {
            this.$set(item, "countTimeStatus", 0);
          }
        }
      });
    },
    // 是否超时
    overTime(item) {
      let startDate, endDate;
      if (isIOS()) {
        startDate = new Date(item.now_time.replace(/-/g, "/"));
        endDate = new Date(item.pre_end_time.replace(/-/g, "/"));
      } else {
        startDate = new Date(item.now_time);
        endDate = new Date(item.pre_end_time);
      }
      let now = startDate.getTime();
      let end = endDate.getTime();
      if (end - now > 0) {
        this.$set(item, "isOverTime", false);
      } else {
        this.$set(item, "isOverTime", true);
      }
    },

    // 监控locaStorage
    watchStorage() {
      const that = this;
      window.addEventListener("setItemEvent", function(e) {
        // 监听setitem的 key ，执行对应的业务逻辑
        if (e.key === "mailTab") {
          if (e.value) {
            that.getDoodsList();
          }
        }
      });
    },

    isIosFun() {
      const u = navigator.userAgent;
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isiOS) {
        this.isIos = true;
      } else {
        this.isIos = false;
      }
    },
    initPage() {
      this.page = {
        defaultPagination: 1,
        pageCount: 8,
        totalPages: 0
      };
    }
  },
  mounted() {
    this.watchStorage();
    this.isIosFun();
    this.$bus.$on("initPage", this.initPage);
    let that = this;
    if (getWidth() <= 768) {
      that.platform = 2;
      that.page.pageCount = 9999;
    } else {
      that.platform = 1;
      that.page.pageCount = 8;
    }

    window.onresize = function() {
      if (that.$refs.productItem) {
        if (getWidth() <= 768) {
          that.platform = 2;
          that.page.pageCount = 9999;
        } else {
          that.platform = 1;
          that.page.pageCount = 8;
        }
      }
    };
    this.getDoodsList();
  },
  beforeDestroy() {
    this.$bus.$off("initPage");
  }
};
</script>

<style lang="less" scoped>
.productItem {
  width: 100%;
  height: 100%;
}

@media screen and (max-width: 768px) {
}
</style>
